<?php

namespace App\Console\Commands\Kms;

use App\Models\Kms\Album\AlbumResourceModel;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

class FixAlbumCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'kms:fixAlbumCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'kms:修复历史数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        AlbumResourceModel::query()->with(["fsUserByUsernameRel", "albumMainRel"])
                          ->each(function (AlbumResourceModel $albumResourceModel) {
                              if ($albumResourceModel->fsUserByUsernameRel) {
                                  $albumResourceModel->setRawAttributes([
                                      "createdByUid" => $albumResourceModel->fsUserByUsernameRel->rmsUserId,
                                      "updatedByUid" => $albumResourceModel->fsUserByUsernameRel->rmsUserId,
                                  ]);
                                  $albumResourceModel->save();

                                  if ($albumResourceModel->albumMainRel->ownerUid != $albumResourceModel->fsUserByUsernameRel->rmsUserId) {
                                      $albumResourceModel->albumMainRel->setRawAttributes([
                                          "ownerUid"     => $albumResourceModel->fsUserByUsernameRel->rmsUserId,
                                          "createdByUid" => $albumResourceModel->fsUserByUsernameRel->rmsUserId,
                                          "updatedByUid" => $albumResourceModel->fsUserByUsernameRel->rmsUserId,
                                      ]);
                                      $albumResourceModel->albumMainRel->save();
                                  }
                              } else {
                                  $this->error($albumResourceModel->id);
                              }
                          });
        return 0;
    }
}
